package liudan.archetype.server;

import java.io.*;
import java.net.Socket;

/**
 * Description:
 * Email: liudan@ucfgroup.com
 * Title
 * Copyright: Copyright (c) 2017
 * User: liudan
 * Created on 2017/2/25 22:57
 */
public class Processor extends Thread {
    private Socket socket;
    private InputStream in;
    private PrintStream out;

    public Processor(Socket socket) {
        this.socket = socket;
        try {
            in = socket.getInputStream();
            out = new PrintStream(socket.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        String fileName = parser(in);
        sendFile(fileName);
    }

    private String parser(InputStream inputStream) {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String fileName = null;
        try {
            String queryMessage = bufferedReader.readLine();
            String[] httpMessage = queryMessage.split(" ");
            System.out.println("query method:" + httpMessage[0] + " || query url:" + httpMessage[1] + " || http version:" + httpMessage[2]);
            fileName = httpMessage[1];
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }

    public void message(int code, String message) {
        out.println("HTTP/1.0 " + code + " query");
        out.println("Content-Type:text/html;charset=utf-8");
        out.println();
        out.println("<html>");
        out.println("<head><title>");
        out.println(message);
        out.println("</title></head>");
        out.println("<body>");
        out.println("<h1>code:"+code+"<br/>error message:"+message+"</h1>");
        out.println("</body>");
        out.println("");
        out.println("</html>");
        out.flush();
        out.close();
    }

    private void sendFile(String fileName) {
        File file = new File("/Users/liudan/Documents/ios" + fileName);
        if (!file.exists()) {
            message(404, "query file not found!");
            return ;
        }
        try {
            InputStream in = new FileInputStream(file);
            byte content[] = new byte[(int) file.length()];
            in.read(content);
            out.println("HTTP/1.0 200 query");
            out.println("Content-Type:text/html;charset=utf-8");
            out.println("content-length:" + content.length);
            out.println();
            out.write(content);
            out.flush();
            out.close();
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
